<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import { getAllRepairRequests, updateRepairRequest, getAllWorkers } from '@/api/adminApi'

// 数据状态
const loading = ref(false)
const searchKeyword = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const detailVisible = ref(false)
const currentRepair = ref({})
const repairList = ref([])
const workers = ref([])

// 统计数据
const stats = ref([
  { label: '待处理', value: 0, class: 'warning' },
  { label: '处理中', value: 0, class: 'info' },
  { label: '已完成', value: 0, class: 'success' },
  { label: '总工单', value: 0, class: 'primary' }
])

// 获取维修人员姓名
const getWorkerName = (workerId) => {
  const worker = workers.value.find(w => w.workId === workerId)
  return worker ? `${worker.name}(${worker.role})` : '未分配'
}

// 获取状态标签类型
const getStatusType = (status) => {
  const types = {
    '待处理': 'warning',
    '处理中': 'primary',
    '已完成': 'success'
  }
  return types[status] || 'info'
}

// 格式化日期
const formatDate = (timestamp) => {
  if (!timestamp) return ''
  return new Date(timestamp).toLocaleString()
}

// 计算属性：过滤后的报修列表
const filteredRepairList = computed(() => {
  if (!searchKeyword.value) return repairList.value
  const keyword = searchKeyword.value.toLowerCase()
  return repairList.value.filter(repair => 
    repair.requestId.toString().includes(keyword) ||
    repair.description.toLowerCase().includes(keyword)
  )
})

// 获取报修列表
const fetchRepairList = async () => {
  loading.value = true
  try {
    const response = await getAllRepairRequests()
    if (response.code === 200) {
      repairList.value = response.data
      updateStats()
    }
  } catch (error) {
    ElMessage.error('获取报修列表失败')
    console.error(error)
  } finally {
    loading.value = false
  }
}

// 获取维修人员列表
const fetchWorkers = async () => {
  try {
    const response = await getAllWorkers()
    if (response.code === 200) {
      workers.value = response.data
    }
  } catch (error) {
    ElMessage.error('获取维修人员列表失败')
    console.error(error)
  }
}

// 更新统计数据
const updateStats = () => {
  const pending = repairList.value.filter(r => r.status === '待处理').length
  const processing = repairList.value.filter(r => r.status === '处理中').length
  const completed = repairList.value.filter(r => r.status === '已完成').length
  
  stats.value[0].value = pending
  stats.value[1].value = processing
  stats.value[2].value = completed
  stats.value[3].value = repairList.value.length
}

// 分配维修人员
const handleAssign = async (repair, workerId) => {
  try {
    const response = await updateRepairRequest({
      requestId: repair.requestId,
      status: '处理中',
      assignedTo: workerId,
      resolvedAt: null
    })
    
    if (response.code === 200) {
      ElMessage.success('分配成功')
      fetchRepairList()
    }
  } catch (error) {
    ElMessage.error('分配失败')
    console.error(error)
  }
}

// 完成维修
const handleComplete = async (repair) => {
  try {
    await ElMessageBox.confirm('确认该维修工单已完成？', '提示')
    
    const response = await updateRepairRequest({
      requestId: repair.requestId,
      status: '已完成',
      assignedTo: repair.assignedTo,
      resolvedAt: new Date().toISOString()
    })
    
    if (response.code === 200) {
      ElMessage.success('工单已完成')
      fetchRepairList()
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('操作失败')
      console.error(error)
    }
  }
}

// 查看详情
const handleDetail = (repair) => {
  currentRepair.value = repair
  detailVisible.value = true
}

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
}

const handleCurrentChange = (val) => {
  currentPage.value = val
}

// 初始化
onMounted(async () => {
  await fetchWorkers()
  await fetchRepairList()
})
</script>

<template>
  <div class="admin-container">
    <h2>报修管理</h2>

    <!-- 顶部统计卡片 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="6" v-for="stat in stats" :key="stat.label">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-value" :class="stat.class">{{ stat.value }}</div>
          <div class="stat-label">{{ stat.label }}</div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 操作栏 -->
    <div class="action-bar">
      <div class="right">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索工单号/描述"
          class="search-input"
          clearable
          @input="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>
    </div>

    <!-- 报修列表 -->
    <el-table 
      :data="filteredRepairList" 
      border 
      v-loading="loading"
    >
      <el-table-column prop="requestId" label="工单号" width="100" />
      <el-table-column prop="description" label="问题描述" show-overflow-tooltip />
      <el-table-column prop="status" label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="getStatusType(row.status)">
            {{ row.status }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="assignedTo" label="维修人员" width="200">
        <template #default="{ row }">
          <el-select 
            v-model="row.assignedTo" 
            placeholder="请选择"
            size="small"
            @change="(value) => handleAssign(row, value)"
          >
            <el-option
              v-for="worker in workers"
              :key="worker.workId"
              :label="`${worker.name}(${worker.role})`"
              :value="worker.workId"
            />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column prop="createdAt" label="报修时间" width="180">
        <template #default="{ row }">
          {{ formatDate(row.createdAt) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" width="180">
        <template #default="{ row }">
          <el-button-group>
            <el-button 
              type="primary" 
              link
              @click="handleComplete(row)"
            >
              完成
            </el-button>
            <el-button 
              type="success" 
              link 
              @click="handleDetail(row)"
            >
              详情
            </el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页器 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 详情对话框 -->
    <el-dialog
      v-model="detailVisible"
      title="报修详情"
      width="600px"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="工单号">{{ currentRepair.requestId }}</el-descriptions-item>
        <el-descriptions-item label="用户ID">{{ currentRepair.userId }}</el-descriptions-item>
        <el-descriptions-item label="报修状态">
          <el-tag :type="getStatusType(currentRepair.status)">
            {{ currentRepair.status }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="维修人员">
          {{ getWorkerName(currentRepair.assignedTo) }}
        </el-descriptions-item>
        <el-descriptions-item label="报修时间" :span="2">
          {{ formatDate(currentRepair.createdAt) }}
        </el-descriptions-item>
        <el-descriptions-item label="完成时间" :span="2">
          {{ formatDate(currentRepair.resolvedAt) || '未完成' }}
        </el-descriptions-item>
        <el-descriptions-item label="问题描述" :span="2">
          {{ currentRepair.description }}
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<style scoped>
.admin-container {
  padding: 20px;
}

.stats-row {
  margin-bottom: 20px;
}

.stat-card {
  text-align: center;
  padding: 20px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 8px;
}

.stat-value.warning { color: #E6A23C; }
.stat-value.success { color: #67C23A; }
.stat-value.info { color: #909399; }
.stat-value.primary { color: #409EFF; }

.stat-label {
  color: #606266;
  font-size: 14px;
}

.action-bar {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 20px;
}

.search-input {
  width: 250px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>